<template>
  <div class="w_h_100">
    <div class="inlet">业务进件 > 业务进件 > <span class="size">{{ name }}</span></div>
    <div class="d_f m_t_10 auto">
      <div class="left ">
        <div class="type_box">
          <div>
            <div class="title">{{ name }}</div>
            <span class="pattern">{{ productCategory == 1 ? "融资 - 单笔" : productCategory == 2 ? '融资 - 批量' :
              productCategory == 3 ? '非融 - 单笔' : '非融 - 批量' }}</span>
          </div>
          <div class="d_f j_c_s_b margin a_i_c">
            <div class="tips">信息录入</div>
            <el-button :icon="Clock" @click="history" :disabled="hisDisabled">加载历史信息</el-button>
          </div>
          <div class="d_f j_c_s_b btn">
            <div class="type d_f  a_i_c j_c_s_a" :class="model.customerType == '1' ? 'active' : ''"
              @click="change('1')">
              <img src="../../assets/nature.png" alt="" v-if="model.customerType == '2'" class="img">
              <img src="../../assets/nature1.png" alt="" v-else class="img">
              <span class="size"> 自然人</span>
            </div>
            <div class="type d_f  a_i_c j_c_s_a" :class="model.customerType == '2' ? 'active' : ''"
              @click="change('2')">
              <img src="../../assets/legalperson.png" alt="" v-if="model.customerType == '1'" class="img">
              <img src="../../assets/legalperson1.png" alt="" v-else class="img">
              <span class="size"> 法人</span>
            </div>
          </div>
          <myform :fields="fields" ref="ruleFrom" :model="model" :inline="false" :options="options" labelPosition="top"
            :rules="rules" class="m_t_16"></myform>
        </div>
        <div class="d_f j_c_s_b btn">
          <div></div>
          <div>
            <el-button type="danger" plain @click="cancel">取消</el-button>
            <el-button type="primary" plain @click="save" v-hasPerm="'saveBusiness'">保存</el-button>
            <el-button type="primary" @click="submit" v-myRepeat v-hasPerm="'submitBusiness'">提交</el-button>
          </div>
        </div>
      </div>
      <div class="right">
        <template v-for="item in records">
          <component class="m_t_20" :isIncoming="isIncoming" :isAudit="false" :code="item.code"
            :customerType="model.customerType" :isVar="false" :productCategory="productCategory" :productId="productId"
            :vars="vars" :agencyName="agencyName" :productName="productName" :nodeObj="nodeObj"
            :is="FormComponents[item.tag]" :isEnabled="item.isEnabled" ref="itemRefs" type="useForm" :unitId="unitId"
            @handleSelect="handleSelect" />
        </template>
      </div>
    </div>
    <el-dialog v-model="dialogVisible" title="合作详情选择" width="700" :before-close="handleClose">
      <div>
        合作选择：
        <el-radio-group v-model="model.agencyData.agencyProductId">
          <el-radio v-for="(item, index) in options.agencyProductId"
            @change="getagencyDetail(model.agencyData.agencyProductId)" :value="item.id">合作{{ index + 1 }}</el-radio>
        </el-radio-group>
      </div>
      <div class="incoming_form">
        <myform :fields="fields1" ref="cooperateForm" :options="options" :model="model.agencyData" :rules="rules"
          labelPosition="top" class="m_t_16">
        </myform>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="query" v-myRepeat>
            确 定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <component class="m_t_20" :is="FormComponents['ryfp']" v-if="taskId" :isEnabled="1" ref="ryfp" type="useForm"
      @resultData="resultData" />
  </div>
</template>
<script lang='ts'>
import { defineComponent, reactive, toRefs, onBeforeMount, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { copy, objectMatching } from '../../utils/date'
import { unitFormGet } from '../../api/system/flowPath'
import { Clock } from '@element-plus/icons-vue'
import { FormComponents } from '../../components/formChildren/myComponents'
import { projectInputAdd, project_inputGetById, agencyProjectList, agencyProjectDetail, runTaskStashSave, historyProject,recordCheck } from '../../api/business'
import { Message } from '../../utils/resetMessage'
import { incomingType } from '../../type/business'
import { FUND_REG } from '../../utils/regular'
import { ElMessageBox } from 'element-plus'
import { runTaskAssign, batchGetById } from '../../api/agent'
const model = {
  bizType: '',
  flowId: '',
  customerType: '1',
  type: '',
  flowAndNodeData: {
    flowId: '',
    deptId: JSON.parse(<string>localStorage.getItem('userVO')).deptId,
    deptName: JSON.parse(<string>localStorage.getItem('userVO')).deptName || '',
    nodeId: '',
    nodeName: '',
    productId: '',
    productCategory: '',
    isBatch: '0'
  },
  custom: {},
  agencyData: {
    agencyProductId: '',
    beginDate: '',//起始日期
    finishDate: '',//截止日期
    amountLimit: '',//总额度-合作额度
    spendingLimit: '',//使用额度
    balanceLimit: '',//剩余额度
    lockMoney: '',
    liability: '',//分责比例
  }
}
export default defineComponent({
  name: '',
  components: {
  },
  setup() {
    const data: incomingType = reactive({
      type: 0,
      hisDisabled: true,
      fields: [
        {
          label: "业务性质",
          prop: 'bizType',
          placeholder: '请选择',
          type: 'select',
          bindLabel: 'name',
          bindValue: 'id',
        },
      ],
      model: copy(model),
      rules: {
        bizType: [
          { required: true, message: '请选择业务性质', trigger: 'blur' },
        ],
        beginDate: [
          { required: true, message: '请选择起始日期', trigger: 'change' },
        ],
        finishDate: [
          { required: true, message: '请选择截止日期', trigger: 'change' },
        ],
        amountLimit: [
          { required: true, message: '请输入合作额度', trigger: 'blur' },
          { pattern: FUND_REG, message: '合作额度格式不正确' }
        ],
        spendingLimit: [
          { required: true, message: '请输入使用额度', trigger: 'blur' },
          { pattern: FUND_REG, message: '使用额度格式不正确' }
        ],
        balanceLimit: [
          { required: true, message: '请输入剩余额度', trigger: 'blur' },
          { pattern: FUND_REG, message: '剩余额度格式不正确' }
        ],
        liability: [
          { required: true, message: '请输入分责比例', trigger: 'blur' },
          { pattern: FUND_REG, message: '分责比例格式不正确' }
        ],
        branchId: [
          { required: true, message: '请选择银行', trigger: 'change' },
        ],
      },
      options: {
        bizType: [
          {
            name: '首次',
            id: 1,
          },
          {
            name: '续保',
            id: 2,
          },
        ],
        agencyProductId: [],
        branchId: [],
      },
      records: [],
      unitId: '',
      productName: '',
      name: "",
      agencyName: [],
      productId: '',
      productCategory: null,
      nodeObj: {
        name: '',
        id: ''
      },
      dialogVisible: false,
      vars: null,
      fields1: [
        {
          label: "起始日期",
          prop: 'beginDate',
          placeholder: '请选择起始日期',
          type: 'date',
          disabled: true,
        },
        {
          label: "截止日期",
          prop: 'finishDate',
          placeholder: '请选择截止日期',
          type: 'date',
          disabled: true,
        },
        {
          label: "合作额度",
          prop: 'amountLimit',
          placeholder: '请输入合作额度',
          type: 'input',
          unit: '元',
          disabled: true,
        },
        {
          label: "使用额度",
          prop: 'spendingLimit',
          placeholder: '请输入使用额度',
          type: 'input',
          unit: '元',
          disabled: true,
        },
        {
          label: "剩余额度",
          prop: 'balanceLimit',
          placeholder: '请输入剩余额度',
          type: 'input',
          unit: "元",
          disabled: true,
        },
        {
          label: "锁定金额",
          prop: 'lockMoney',
          placeholder: '锁定金额',
          type: 'input',
          unit: "元",
          disabled: true,
        },
        {
          label: "分责比例",
          prop: 'liability',
          placeholder: '请输入分责比例',
          type: 'input',
          unit: "%",
          disabled: true,
        },
      ],
      taskId: '',
      ids: [],
      hisVal: '',
      isIncoming: false,
      // disabledDates: {
      //   beginDate: (date: Date) => {
      //     return date.getTime() > new Date(data.model.agencyData.finishDate).getTime()
      //   },
      //   finishDate: (date: Date) => {
      //     return date.getTime() < new Date(data.model.agencyData.beginDate).getTime() - 8.64e7;
      //   }
      // }
    })
    const itemRefs = ref([])
    const ruleFrom = ref()
    const route = useRoute()
    const cooperateForm = ref()
    const router = useRouter()
    const ryfp = ref()
    onBeforeMount(() => {
      methods.getInfo(route.query.id as string)
      if (route.query.isBatch == '1') {
        data.isIncoming = true
      }

    })
    const methods = {
      getList(id) {
        agencyProjectList({ id: id, productId: data.productId }).then((res: any) => {
          data.options.agencyProductId = res
          if (res.length > 0) {
            data.model.agencyData.agencyProductId = res[0].id
            methods.getagencyDetail(data.model.agencyData.agencyProductId)
          }
        })
      },
      //点击合作机构获取机构信息
      getagencyDetail(id) {
        agencyProjectDetail({ id: id, }).then((res: any) => {
          data.model.agencyData = objectMatching(res, data.model.agencyData)
        })
      },
      getInfo(id: string | number) {
        if (route.query.isBatch == '1') {
          batchGetById({ id: id }).then((res: any) => {
            data.name = res.name
            data.productName = res.productName
            data.model.flowId = res.flowId
            data.productId = data.model.flowAndNodeData.productId = res.productId
            data.model.projectId = res.projectId
            data.agencyName = res.ids
            data.vars = res.vars
            data.model.bizType = res.vars.bizType
            data.productCategory = data.model.type = data.model.flowAndNodeData.productCategory = res.productCategory
            data.model.flowAndNodeData.flowId = res.flowId
            data.nodeObj = res.node[0]
            methods.change('1')
            methods.getData(res.unitId)
            if (res.productCategory == 1 || res.productCategory == 3) {
              if (data.model.customerType == 1) {
                methods.handleSelect({ prop: 'idCard', value: res.vars.rzServiceData.baseDataMateIdCard })

              } else {
                methods.handleSelect({ prop: 'usci', value: res.vars.rzServiceData.usci })
              }
            } else {
              if (data.model.customerType == 1) {
                methods.handleSelect({ prop: 'idCard', value: res.vars.frzServiceData.baseDataMateIdCard })

              } else {
                methods.handleSelect({ prop: 'usci', value: res.vars.frzServiceData.usci })
              }
            }

          })
        } else {
          project_inputGetById({ id: id }).then((res: any) => {
            data.name = res.name
            data.productName = res.productName
            data.model.flowId = res.flowId
            data.productId = data.model.flowAndNodeData.productId = res.productId
            data.agencyName = res.ids

            data.productCategory = data.model.type = data.model.flowAndNodeData.productCategory = res.productCategory
            data.model.flowAndNodeData.flowId = res.flowId
            data.nodeObj = res.node[0]
            methods.change('1')
            methods.getData(res.unitId)

          })
        }

      },
      getData(id: string | number) {
        unitFormGet({ id: id }).then((res: any) => {
          res.forms.map(item => {
            if (item.category == 1) {
              item.code = item.tag
              item.tag = 'customize'
            }
          })
          data.records = res.forms.filter((item: any) => {
            return item.isEnabled == 1
          })
          data.unitId = res.id
        })
      },
      //加载历史记录
      history() {
        historyProject({ id: data.hisVal }).then((res: any) => {
          data.vars = res
          if (res) {
            // data.model.customerType = String(res.rzServiceData.customerType)
          }
          itemRefs.value.map((item: any) => {
            if (item.changeCustomerType) {
              item.changeVars()
            }
          })
        })
      },
      //选择自然人还是法人
      change(num: string) {
        if(data.isIncoming)return
        data.model.customerType = num
        itemRefs.value.map((item: any) => {
          if (item.changeCustomerType) {
            item.changeCustomerType(num)
          }
        })
      },
      //提交按钮校验所有表单是否通过校验，通过后拉起弹窗
      submit() {
        recordCheck({ id: data.hisVal }).then((ree: any) => {
          console.log(ree);
          if(ree>0&&data.model.bizType==1){
          Message({type:'error',message:'当前不能首次担保'})
          return
      
        }
        let arr = []
        ruleFrom.value.verification().then(() => {

          itemRefs.value.map((item: any, index: number) => {
            if (item.resultData) {
              item.resultData().then((res: any) => {
                let ress =copy(res)
                data.model = Object.assign(ress, data.model);
                arr.push(true)
              }).catch(() => {
                arr.push(false)
              })
            }
          })

          setTimeout(() => {

            if (arr.every((item1: any) => item1) && arr.length == itemRefs.value.length) {
              if (route.query.isBatch as string) {
                methods.supplement()
              } else {
                let id = ''
                if (data.productCategory == 1 || data.productCategory == 2) {
                  id = data.model.projectData.agencyId
                } else {
                  id = data.model.frzServiceData.agencyId
                }

                methods.getList(id)
                data.dialogVisible = true
              }

            } if (arr.length != itemRefs.value.length) {
              Message({ type: 'error', message: '表单有未通过校验，请检查表单配置' })
            }
          }, 500)
        })


      })
       
       
  
      },
      //业务进件选择自然人跟法人进行弹窗
      handleSelect(obj: any) {
        if (obj.prop == 'customerType') {
          methods.change(obj.value)
        } else if (obj.prop == 'idCard') {
          data.hisVal = obj.value
          if (obj.value) {

            data.hisDisabled = false
          } else {
            data.hisDisabled = true
          }

        } else if (obj.prop == 'usci') {
          data.hisVal = obj.value
          if (obj.value) {

            data.hisDisabled = false
          } else {
            data.hisDisabled = true
          }
        }
      },
      //关闭弹窗
      handleClose() {
        data.dialogVisible = false
      },
      //待推客户进件补充信息不进行弹出窗
      supplement() {
        if (route.query.isBatch) {
          data.model.isBatch = route.query.isBatch as string
        }
        let num = ''
        if (data.productCategory == 1 || data.productCategory == 2) {
          num = data.model.projectData.applyAmount
        } else {
          num = data.model.frzServiceData.guaMoney
        }
        data.model.bizTag = 'projectInput'
        // if (data.model.agencyData.balanceLimit < num) return Message({ type: 'error', message: '剩余额度不足，请重新填写' })
        projectInputAdd(data.model).then((res: any) => {
          data.dialogVisible = false
          if (res.length == 0) {
            Message({ type: 'success', message: '保存成功' })
            if (data.productCategory == 2) {
              router.push('/agent/custom/financing')
            } else if (data.productCategory == 4) {
              router.push('/agent/custom/noFinancing')
            }
          } else {
            data.ids = res
            data.taskId = res[0]
          }
        })
      },
      //选择合作之后进行提交业务进件信息
      query() {
        cooperateForm.value.verification().then(() => {
          if (route.query.isBatch) {
            data.model.isBatch = route.query.isBatch as string
          }
          let num = ''
          if (data.productCategory == 1 || data.productCategory == 2) {
            num = data.model.projectData.applyAmount
          } else {
            num = data.model.frzServiceData.guaMoney
          }
          data.model.bizTag = 'projectInput'
          if (data.model.agencyData.balanceLimit < num) return Message({ type: 'error', message: '剩余额度不足，请重新填写' })
         data.model. flowAndNodeData.deptId=JSON.parse(<string>localStorage.getItem('userVO')).deptId
          data.model.flowAndNodeData.deptName=JSON.parse(<string>localStorage.getItem('userVO')).deptName || ''
          projectInputAdd(data.model).then((res: any) => {
            data.dialogVisible = false
            if (res.length == 0) {
              Message({ type: 'success', message: '保存成功' })
              if (data.productCategory == 1) {
                router.push('/agent/singleFinancing/front')
              } else if (data.productCategory == 3) {
                router.push('/agent/noFinancingSingle/front')
              } else if (data.productCategory == 2) {
                router.push('/agent/financingBatch/front')
              } else if (data.productCategory == 4) {
                router.push('/agent/noFinancingBatch/front')
              }
            } else {
              data.ids = res
              data.taskId = res[0]
            }
          })
        })
      },
      //取消保存
      cancel() {
        ElMessageBox.confirm(
          '当前信息将不再保存?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
          .then(() => {
            router.go(-1)
          })
      },
      //保存
      save() {
        let arr = []
        itemRefs.value.map((item: any, index: number) => {
          if (item.saveData) {
            item.saveData().then((res: any) => {
              data.model = Object.assign(res, data.model);
              arr.push(true)
            }).catch(() => {
              arr.push(false)
            })
          }
        })
        setTimeout(() => {
          if (arr.every((item1: any) => item1) && arr.length == itemRefs.value.length) {
            ElMessageBox.confirm(
              '当前信息将进入暂缓区，是否继续?',
              '提示',
              {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
              }
            )
              .then(() => {
                let findKey = ''
                if (data.productCategory == 1 || data.productCategory == 2) {
                  if (data.model.customerType == '1') {
                    findKey = data.model.rzServiceData.baseDataIdCard
                  } else {
                    findKey = data.model.rzServiceData.usci
                  }
                } else {
                  if (data.model.customerType == '1') {
                    findKey = data.model.frzServiceData.baseDataIdCard
                  } else {
                    findKey = data.model.frzServiceData.usci
                  }
                }
                runTaskStashSave({ findKey: findKey, var: data.model }).then((res: any) => {
                  Message({ type: 'success', message: '保存成功' })
                })
              })
          }
        }, 500)
      },
      resultData(val) {

        runTaskAssign({ taskId: data.taskId, empId: val.empId }).then(() => {
          Message({ type: 'success', message: '提交成功' })
          ryfp.value.clearValue()
          data.ids = data.ids.filter((item: any) => {
            return item != data.taskId
          })
          if (data.ids.length > 0) {
            data.taskId = data.ids[0]
          } else {
            if (data.productCategory == 1) {
              router.push('/agent/singleFinancing/front')
            } else if (data.productCategory == 3) {
              router.push('/agent/noFinancingSingle/front')
            } else if (data.productCategory == 2) {
              router.push('/agent/financingBatch/front')
            } else if (data.productCategory == 4) {
              router.push('/agent/noFinancingBatch/front')
            }
          }
        })
      }
    }
    return {
      ...toRefs(data),
      ...methods, itemRefs, ryfp,
      Clock, ruleFrom, FormComponents, cooperateForm
    }
  }
})
</script>
<style scoped lang='scss'>
.auto {
  height: calc(100% - 30px);
}

.left {
  width: 24%;

  .type_box {
    width: calc(100% - 40px);
    padding: 32px 20px;
    background: linear-gradient(177deg, #F5F9FF 2%, #FFFFFF 62%);
    border-image: linear-gradient(158deg, rgba(155, 188, 235, 0.5) 4%, rgba(102, 142, 197, 0) 84%) 1;
    border-radius: 6px;
    box-shadow: 5px 5px 5px -2px rgba(9, 20, 29, 0.03);
  }

  .type {
    background: rgba(220, 220, 220, 0.4);
    border-radius: 3px;
    width: 42%;
    height: 3.125vw;
    backdrop-filter: blur(10px);
    cursor: pointer;
    color: rgba(0, 0, 0, 0.4);
    font-size: 0.9375vw;
    padding: 0px 5px;
  }

  .active {
    border: 1px solid #1878FF;
    background: #F7FBFF;
    backdrop-filter: blur(10px);
    color: #1878FF;
  }

  .img {
    // width: 51px;
    height: 50px;
    margin-top: 5px;
  }

  .size {
    // margin-left: 1.3vw;
  }

  .title {
    color: rgba(22, 35, 55, 0.9);
    font-size: 32px;
  }

  .pattern {
    color: rgba(22, 35, 55, 0.4);
    font-size: 14px;
  }

  .margin {
    margin-top: 37px;
  }

  .tips {
    color: #3D3D3D;
    font-size: 16px;
  }

  .btn {
    margin-top: 32px;
  }
}

.right {
  width: calc(76% - 84px);
  padding: 10px 32px;
  background: #fff;
  margin-left: 16px;
  border-radius: 6px;
  overflow-y: auto;
  height: calc(100% - 20px);
}
</style>
<style lang="scss">
.type_box {
  .el-select {
    width: 100% !important;
  }
}

.incoming_form {

  .el-input,
  .el-select {
    width: 190px !important;
  }
}
</style>